﻿using Kingdee.BOS.App;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using LM.YF.K3Cloud.Plugin.Models;
using System;
using System.ComponentModel;

namespace LM.YF.K3Cloud.Plugin
{
    /// <summary>
    /// 鹿奔 240413
    /// </summary>
    [Description("销售订单下推发货通知单的单据转换插件（获取运输路线）"), HotUpdate]
    public class DiliveryOrderCvtPlugin : AbstractConvertPlugIn
    {
        #region MyRegion

        /// <summary>
        /// 运输路线
        /// </summary>
        readonly ElementKeySchema F_RDLV_route = new ElementKeySchema
        {
            FormKey = "F_RDLV_route",
            DbKey = "F_RDLV_ROUTE",
            OrmKey = "F_RDLV_route"
        };

        /// <summary>
        /// 发货组织
        /// </summary>
        readonly ElementKeySchema FDeliveryOrgID = new ElementKeySchema
        {
            FormKey = "FDeliveryOrgID",
            DbKey = "FDELIVERYORGID",
            OrmKey = "DeliveryOrgID"
        };

        /// <summary>
        /// 客户
        /// </summary>
        readonly ElementKeySchema FCustomerID = new ElementKeySchema
        {
            FormKey = "FCustomerID",
            DbKey = "FCUSTOMERID",
            OrmKey = "CustomerID"
        };

        /// <summary>
        /// 承运商
        /// </summary>
        readonly ElementKeySchema FCarrierID = new ElementKeySchema
        {
            FormKey = "FCarrierID",
            DbKey = "FCARRIERID",
            OrmKey = "CarrierID"
        };

        /// <summary>
        /// 销售主体
        /// </summary>
        readonly ElementKeySchema F_RDLV_saler2 = new ElementKeySchema
        {
            FormKey = "F_RDLV_saler2",
            DbKey = "F_RDLV_SALER2",
            OrmKey = "F_RDLV_saler2"
        };

        #endregion

        public override void AfterConvert(AfterConvertEventArgs e)
        {
            base.AfterConvert(e);

            ExtendedDataEntity[] extendedDataEntities = e.Result.FindByEntityKey("FBillHead");
            for (int i = 0, l = extendedDataEntities.Length; i < l; i++)
            {
                var extendedDataEntity = extendedDataEntities[i];

                var regionId = Convert.ToInt32((extendedDataEntity[FCustomerID.OrmKey] as DynamicObject)?["F_RDLV_Region_Id"]);
                var stockOrgId = Convert.ToInt32((extendedDataEntity[FDeliveryOrgID.OrmKey] as DynamicObject)?["Id"]);
                var saleBodyId = Convert.ToInt32((extendedDataEntity[F_RDLV_saler2.OrmKey] as DynamicObject)?["Id"]);

                var routeData = SalesOrderBillPlugin.GetRoute(Context, regionId, stockOrgId, saleBodyId);
                if (routeData.Failure == null)
                {
                    IViewService viewService = ServiceHelper.GetService<IViewService>();

                    var routeFileld = e.TargetBusinessInfo.GetField(F_RDLV_route.FormKey) as BaseDataField;
                    var routeObjs = viewService.LoadFromCache(Context, new object[] { routeData.RouteId }, routeFileld.RefFormDynamicObjectType);
                    extendedDataEntity[F_RDLV_route.OrmKey] = routeObjs[0];
                    extendedDataEntity[F_RDLV_route.OrmKey + "_Id"] = routeData.RouteId;

                    var carrierFileld = e.TargetBusinessInfo.GetField(FCarrierID.FormKey) as BaseDataField;
                    var carrierObjs = viewService.LoadFromCache(Context, new object[] { routeData.CarrierId }, carrierFileld.RefFormDynamicObjectType);
                    extendedDataEntity[FCarrierID.OrmKey] = carrierObjs[0];
                    extendedDataEntity[FCarrierID.OrmKey + "_Id"] = routeData.CarrierId;

                    // 这会导致写到界面上的数值，无法通过保存按钮存入到数据库中
                    // var objRoute = GenerateDynamicObject("RDLV_TransfRute", routeId.ToString());
                }
            }
        }
    }
}
